<!--时段号源，时间出错数据再编辑列表-->
<template>
  <div>
    <el-dialog
      title="时间出错，超出班次时间范围"
      :visible.sync="appoErrorListVisible"
      :destroy-on-close="true"
      width="70%"
      class="ky-dialog">
      <div class="appoError-wrap">
        <el-table
          :data="tableData"
          class="ky-table ky-table-sm"
          border
          v-loading="loading"
          style="width: 100%">
          <!-- <el-table-column prop="hospitalName" label="医院" min-width="170"></el-table-column> -->
          <el-table-column label="院区/部门/设备/机房" min-width="180">
            <template slot-scope="scope">
              <span>{{scope.row.depArea}}/{{scope.row.dep}}/{{scope.row.modality}}/{{scope.row.checkRoom}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="appointmentStatus" label="状态" width="100">
            <template slot-scope="scope">
              <div v-if="errorType === 'template'" class="status_tag" :class="statusFlr2(scope.row.status)">{{scope.row.status}}</div>
              <div v-else class="status_tag" :class="statusFlr(scope.row.appointmentStatus)">{{scope.row.appointmentStatus}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="appointmentDate" label="检查日期" width="200" :formatter="dateFormatter">
            <template slot-scope="scope">
              <span :class="{date_expire: scope.row.expire}">{{dateFormatter('','',scope.row.appointmentDate)}} {{scope.row.week}} {{scope.row.checkClass}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="beginTime" label="时段时间" min-width="270">
            <template slot-scope="scope">
              <div v-if="scope.row.modify">
                <el-time-select
                  ref="timeselect_start"
                  placeholder="起始时间"
                  v-model="editData.beginTime"
                  :picker-options="startTimePickerOption"
                  style="width: 120px;">
                </el-time-select>
                <el-time-select
                  ref="timeselect_end"
                  placeholder="结束时间"
                  v-model="editData.endTime"
                  :picker-options="endTimePickerOption"
                  style="width: 120px;">
                </el-time-select>
              </div>
              <span v-else>{{scope.row.beginTime}}-{{scope.row.endTime}} （班次：{{scope.row.selectTimeStart}}-{{scope.row.selectTimeEnd}}）</span>
            </template>
          </el-table-column>
          <el-table-column prop="checkNum" label="检查数量" width="80"></el-table-column>
          <el-table-column prop="initialNum" label="初始" width="80"></el-table-column>
          <el-table-column prop="reserveNum" label="预留" width="80"></el-table-column>
          <el-table-column prop="addNum" label="追加" width="80"></el-table-column>
          <!-- <el-table-column prop="checkClass" label="班次" width="80"></el-table-column>
          <el-table-column prop="week" label="星期" width="80"></el-table-column> -->
          <el-table-column label="操作" width="160" fixed="right" v-permission="'YJYY10001001003'" v-if="!expire">
            <template slot-scope="scope">
              <template v-if="scope.row.appointmentStatus === '正常预约'">
                <el-button
                  type="success"
                  size="small"
                  v-if="!scope.row.modify"
                  @click.stop="statusChange(scope.row, scope.$index)"
                  :disabled="flrDate(scope.row.appointmentDate)"
                >状态</el-button>
              </template>
              <template v-else>
                <el-button
                  v-if="!scope.row.modify"
                  type="primary"
                  size="small"
                  @click.stop="edit(scope.row, scope.$index)"
                  :disabled="flrDate(scope.row.appointmentDate)"
                >编辑</el-button>
                <el-button
                  v-else
                  type="warning"
                  size="small"
                  @click.stop="save(scope.row, scope.$index)"
                >确定</el-button>
              </template>
              <el-button
                type="danger"
                size="small"
                @click.stop="delSend(scope.row, scope.$index)"
                :disabled="flrDate(scope.row.appointmentDate)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="tips tips_error" v-if="expire">提示：存在今天及今天之前的出错预约号源，暂不可修改！</div>
        <div class="tips" v-else>提示：以上预约时段为时间出错，超出班次时间范围，编辑修改后暂存到模板，<span style="color: #f00;">当前数据存入时段设置模板。需{{errorType === 'template'?'保存提交':'暂存、发布'}}后才算修改保存完成！</span></div>
      </div>
      <span slot="footer" class="">
        <el-button size="mini" @click="appoErrorListVisible = false">关闭</el-button>
        <el-button size="mini" v-if="tableData.length>0 && !expire" type="primary" @click="appoErrorInsert">保存到模板</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改预约时段状态"
      :visible.sync="dialogVisible"
      :destroy-on-close="true"
      width="400px">
      <div>
        <el-form
          ref="formdata"
          :inline="true"
          :model="formdata"
          class="ky-form-inline ky-form-inline-sm">
          <el-form-item label="时段状态">
            <el-select size="mini" v-model="formdata.appointmentStatus" placeholder="请选择">
              <el-option
                v-for="item in appointmentStatusOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <slot name="tips"></slot>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
        <el-button size="small" type="primary" @click="eidtStatusSend">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  updateappointmentstatus
} from '@/api/api'
import { Options } from '@/utils/constant'
import { dateFormatter } from '@/utils/validate'
export default {
  props: {
    errorType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      appoErrorListVisible: false,
      loading: false,
      expire: false,
      insertFlag: false,
      tableData: [],
      editData: {
        endTime: '',
        beginTime: ''
      },
      // 设置时间选项参数
      stepTime: window.g.DEFAULTSTEPTIME || '00:30',
      startTime: '00:00',
      endTime: '24:00',

      dialogVisible: false,
      statusRow: null,
      statusIndex: null,
      formdata: {
        appointmentStatus: '计划排班'
      },
      appointmentStatusOptions: Options.appointmentStatusOptions
    }
  },
  computed: {
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    ISUSE_DEFAULTSTEPTIME() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.ISUSE_DEFAULTSTEPTIME) || window.g.ISUSE_DEFAULTSTEPTIME || false
    },
    startTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        maxTime: this.editData.endTime
      }
    },
    endTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        minTime: this.editData.beginTime
      }
    }
  },
  methods: {
    show() {
      this.appoErrorListVisible = true
    },
    init(data) {
      let appConfig = this.$store.state.settings.appConfig
      if (this.ISUSE_DEFAULTSTEPTIME) {
        this.stepTime = (appConfig && appConfig.baseConfig && appConfig.baseConfig.DEFAULTSTEPTIME) || window.g.DEFAULTSTEPTIME || '00:30'
      }
      console.log('errorList:====', data)
      const _data = JSON.parse(JSON.stringify(data))
      this.expire = false
      if (_data.length === this.tableData.length && this.insertFlag) {
        this.insertFlag = false
        this.$message.info('时间出错数据修改无效，请重新尝试！')
      }
      _data.forEach(item => {
        item.beginTime = item.oldBeginTime ? item.oldBeginTime.slice(0, 5) : item.beginTime.slice(0, 5)
        item.endTime = item.oldEndTime ? item.oldEndTime.slice(0, 5) : item.endTime.slice(0, 5)
        item.modify = false
        item.expire = false
        if (new Date(item.appointmentDate).getTime() < new Date().getTime()) {
          item.expire = true
          this.expire = true
        }
      })
      this.tableData = [..._data]
      if (this.tableData.length > 0) {
        this.appoErrorListVisible = true
      } else {
        this.appoErrorListVisible = false
      }
    },
    // 删除
    delSend(row, index) {
      this.$confirm('删除预约时段，是否继续？（该删除为展示数据删除，需机房号源数据暂存、发布或保存提交后才生效）', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.tableData.splice(index, 1)
        this.$emit('errorChange', JSON.parse(JSON.stringify(this.tableData)))
      }).catch(() => {})
    },
    // 编辑
    edit(row, index) {
      const _td = this.tableData
      _td.forEach((item, idx) => {
        if (index === idx) {
          item.modify = true
        } else {
          item.modify = false
        }
      })
      this.tableData = [..._td]
      this.startTime = this.getEndTimeM(row.selectTimeStart ? row.selectTimeStart.split('-')[0] : '00:00')
      this.endTime = this.getEndTimeM(row.selectTimeEnd ? row.selectTimeEnd.split('-')[0] : '24:00')
      this.editData.beginTime = row.beginTime.slice(0, 5)
      this.editData.endTime = row.endTime.slice(0, 5)
    },
    // 保存
    save(row, index) {
      const _td = this.tableData
      _td[index].modify = false
      _td[index].beginTime = this.getEndTime(this.editData.beginTime)
      _td[index].endTime = this.getEndTime(this.editData.endTime)
      this.tableData = JSON.parse(JSON.stringify(_td))
      // this.editData.beginTime = 'null'
      // this.editData.endTime = 'null'
    },
    // 状态
    statusChange(row, index) {
      this.dialogVisible = true
      this.statusRow = row
      this.statusIndex = index
      this.formdata.appointmentStatus = row.appointmentStatus
    },
    // 状态修改提交
    eidtStatusSend() {
      this.dialogVisible = false
      const params = {
        hospitalCode: this.statusRow.hospitalCode,
        ids: [this.statusRow.id],
        appointmentStatus: this.formdata.appointmentStatus
      }
      this.loading = true
      updateappointmentstatus(params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.$message.success('预约时段状态修改成功！')
          this.tableData[this.statusIndex].appointmentStatus = this.formdata.appointmentStatus
        }
      })
    },
    // 修改完后保存数据，插入到时段设置模板
    appoErrorInsert() {
      this.insertFlag = true
      this.$emit('errorInsert', this.tableData)
      // this.appoErrorListVisible = false
    },
    statusFlr(status) {
      switch (status) {
        case '正常预约':
          return 'status_success'
        case '节假日':
          return 'status_danger'
        case '暂停预约':
        case '设备故障':
          return 'status_warn'
        case '计划排班':
          return 'status_default'
        default:
          return 'status_grey'
      }
    },
    statusFlr2(status) {
      switch (status) {
        case '启用':
          return 'status_default'
        case '停用':
          return 'status_grey'
        default:
          return 'status_grey'
      }
    },
    flrDate(rowDate) {
      // return new Date(dateFormatter(rowDate, false)).getTime() < new Date().getTime()
      return false
    },
    dateFormatter(row, column, cellValue, index) {
      return cellValue ? dateFormatter(cellValue, false) : ''
    },
    // 判断是否位24点，如果24点，则转为 23：59
    getEndTime(time) {
      if (!time) return ''
      const t = time.split(':')
      return t[0] * 1 === 24 ? '23:59' : time
    },
    getEndTimeM(time) {
      return time === '23:59' ? '24:00' : time
    }
  }
}
</script>

<style lang="scss" scoped>
$appoSuccessColor: #0bd677;
$appoSuccessBgColor: rgba(11, 214, 119, 0.08);
$appoSuccessBrColor: rgba(11, 214, 112, 0.4);
$appoDefaultColor: #1890FF;
$appoDefaultBgColor: rgba(26, 144, 255, 0.08);
$appoDefaultBrColor: rgba(24, 143, 255, 0.4);
$appoDangerColor: #E37470;
$appoDangerBgColor: rgba(227, 116, 112, 0.08);
$appoDangerBrColor: rgba(235, 79, 79, 0.4);
$appoWarnColor: #FF8618;
$appoWarnBgColor: rgba(255, 136, 24, 0.08);
$appoWarnBrColor: rgba(255, 136, 24, 0.4);
$appoGreyColor: #919398;
$appoGreyBgColor: rgba(145, 147, 152, 0.08);
$appoGreyBrColor: rgba(145, 147, 152, 0.4);
.status_tag{
  display: inline-block;
  padding: 2px 6px;
  border-radius: 3px;
  border: solid 1px $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  font-size: 12px;
  color: $appoDefaultColor;
}
.status_default{
  border-color: $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  color: $appoDefaultColor;
}
.status_success{
  border-color: $appoSuccessBrColor;
  background-color: $appoSuccessBgColor;
  color: $appoSuccessColor;
}
.status_danger{
  border-color: $appoDangerBrColor;
  background-color: $appoDangerBgColor;
  color: $appoDangerColor;
}
.status_warn{
  border-color: $appoWarnBrColor;
  background-color: $appoWarnBgColor;
  color: $appoWarnColor;
}
.status_grey{
  border-color: $appoGreyBrColor;
  background-color: $appoGreyBgColor;
  color: $appoGreyColor;
}
.appoError-wrap{
  padding: 15px 15px 0;
  .tips{
    margin-top: 20px;
    color: #333;
  }
  .tips_error{
    color: #f00;
  }
}
.date_expire{
  color: #f00;
}
</style>
